import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from './utils/get-page-title'
// 创建白名单
const whiteList = ['/login', '/404']

// 创建前置守卫
router.beforeEach(async(to, from, next) => {
  // 获取到token
  const token = store.state.user.token
  // 显示进度条
  NProgress.start()
  if (token) {
    // 判断访问是否登录到login
    if (to.path === '/login') {
      next('/')
    } else {
      // 报10002 这个状态码的时候才会有
      router.myrouter = to.fullpath

      if (!store.getters.userId) {
        // 如果存在 token，访问的是其他页面，直接放行
        const menus = await store.dispatch('user/getUserInfo')

        // 根据用户实际的权限 menus 从 asyncRoutes 中过滤出用户能访问的页面
        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })

        router.addRoutes(filterRoutes)

        // 404 page must be placed at the end !!!
        filterRoutes.push(
          { path: '*', redirect: '/404', hidden: true }
        )

        // 将动态路由传递给 mutation 方法，进行合并
        store.commit('permission/setRoutes', filterRoutes)

        // 解决刷新出现的白屏bug
        next({
          path: to.fullPath, // 保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        // 取到最终路由(静态路由,筛选好的路由)
        let allPath = store.state.permission.routes.map(item => item.path)

        const otherPath = [
          '/dashboard',
          '/employees/detail'
        ]
        allPath = [...allPath, ...otherPath]
        // 首先判断要访问的路由是不是在最终路由中
        // 同时判断要访问的路由时不是以employess 开头
        if (!allPath.includes(to.path) && !to.path.startsWith('/employees/detail')) {
          if (!router.myrouter) {
            next('/')
          } else {
            next('/404')
          }
        } else {
          next()
        }
      }
    }
  } else {
    // 判断是否在白名单中
    // 如果在白名单中,就跳转到白毛巾那个单中
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // 如果不在白名单中就跳转到登录页
      next('/login')
    }
  }
  // 隐藏进度条
  NProgress.done()
})

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach((to, from) => {
  // 隐藏进度条
  NProgress.done()
})

//
//  import { Message } from 'element-ui'
//  import NProgress from 'nprogress' // progress bar
//  import 'nprogress/nprogress.css' // progress bar style
//  import { getToken } from '@/utils/auth' // get token from cookie
//  import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasGetUserInfo = store.getters.name
//       if (hasGetUserInfo) {
//         next()
//       } else {
//         try {
//           // get user info
//           await store.dispatch('user/getInfo')

//           next()
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done()
// })
